package com.dhecp.project.storage.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.config.Global;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.DateUtils;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.core.utils.PdfUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductActiveComponent;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.service.ModuleNidAndBidService;
import com.dhecp.project.storage.domain.OfflinePurchaseStorage;
import com.dhecp.project.storage.service.OfflinePurchaseStorageService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 仓储 线下入库单
 * @author: hlf
 * @create: 2022-09-01 16:42
 */
@Controller
@RequestMapping("/storage/offlinepurchasestorage")
public class OfflinePurchaseStorageController extends BaseModuleController {

    private String prefix = "storage/offlinepurchasestorage";
    private String moduleTable = ModuleTable.OFFLINE_PURCHASE_STORAGE;
    private String moduleTableZJ = ModuleTable.PRODUCT_ACTIVE_COMPONENT;
    @Autowired
    private OfflinePurchaseStorageService storageService;
    @Autowired
    private ModuleNidAndBidService moduleNidAndBidService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("storage:offlinepurchasestorage:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
    	
//    	System.out.println("params---" + JSON.toJSONString(params));
    	
        params.put("moduleTable", moduleTable);
        params.put("entity", new OfflinePurchaseStorage()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/offlinepurchasestorage"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "offlinepurchasestorage");
        Object importFields = dictionaryForFieldService.queryFieldFrontImport(params); //导入模板字段
        mv.addObject("importFields", importFields);	//导入模板字段

        return mv;
    }

    /**
     *@Description: 打开制单页
     *@Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("storage:offlinepurchasestorage:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params){
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new OfflinePurchaseStorage()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/offlinepurchasestorage_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:offlinepurchasestorage:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try{
            Map<String, Object> headData = new HashMap<String, Object>();		//表头的业务数据
            OfflinePurchaseStorage businessData = storageService.queryFirstRecord(params);
            if (businessData == null){ //未查询到对应单据，页面初始化值
                ModuleNidAndBid moduleNidAndBid = moduleNidAndBidService.queryModuleNidAndBidInitial(params);
                OfflinePurchaseStorage newData = new OfflinePurchaseStorage();
                newData.setNid("0");
                newData.setBid(moduleNidAndBid.getBid());
                newData.setCreateTime(new Date());
                newData.setCid(ShiroUtils.getMandatorCid());
                newData.setCidName(ShiroUtils.getMandatorCidName());
                newData.setbUser(ShiroUtils.getMandatorId());
                newData.setbUserName(ShiroUtils.getMandatorName());
                newData.setbDept(ShiroUtils.getMandatorDeptPath());
                newData.setbDeptName(ShiroUtils.getMandatorDeptName());
                newData.setaUser(ShiroUtils.getUserId());
                newData.setaUserName(ShiroUtils.getUserName());
                newData.setaDept(ShiroUtils.getUserDeptPath());
                newData.setaDeptName(ShiroUtils.getUserDeptName());
                newData.setGoodsAllocation("");
                headData = TypeUtils.entityToMap(newData);
            }else{
                headData = TypeUtils.entityToMap(businessData);
                vType = businessData.getEffectStock();
            }
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);

            mv.addObject("nowTimeStr", DateUtils.getDate());    //当前日期
            mv.addObject("enableEdit", vType?0:enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）

            return mv;
        }catch(Exception e){
            return this.gotoModelAndViewErrorPage(e.getMessage());	//详细信息
        }

    }

    /**
     *@Description: 打开流转页
     *@Param: [params] fType 必要参数：审核类型（flow_go：流转，flow_back：退回）
     *@Param: [params] infoMap 必要参数：非网格字段（包括所有显示和隐藏的字段），json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:offlinepurchasestorage:flow")
    @PostMapping("/flowpage")
    @ResponseBody
    public AjaxResult flowPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("prefix", prefix);
        return openFlowPage(params);
    }

    /**
     *@Description: 制单页 明细数据
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:offlinepurchasestorage:list")
    @GetMapping("/listbynid")
    @ResponseBody
    public TableDataInfo listByNid(@RequestParam Map<String, Object> params){
        if (params.get("nid") == null || params.get("nid") == ""){
            return getDataTable(MessageUtils.message("module.error.lack.nid"));
        }
        params.put("moduleTable", moduleTable);
        List<OfflinePurchaseStorage> list = new ArrayList<OfflinePurchaseStorage>();
        try {
            list = storageService.queryListByNid(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:offlinepurchasestorage:view")
    @GetMapping("/lastnid")
    @ResponseBody
    public AjaxResult lastNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = storageService.queryLastNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 11:40
     */
    @RequiresPermissions("storage:offlinepurchasestorage:view")
    @GetMapping("/nextnid")
    @ResponseBody
    public AjaxResult nextNid(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = storageService.queryNextNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 查询页 列表数据
     *@Param: [params]
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:offlinepurchasestorage:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<OfflinePurchaseStorage> list = new ArrayList<OfflinePurchaseStorage>();
        try {
            list = storageService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     *@Description: 数据导出Excel
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:offlinepurchasestorage:export")
    @Log(title = "线下入库单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new OfflinePurchaseStorage());
        if (params.get("num").equals("0")){
            params.put("state", "未入库");
        } else {
            params.put("state", "已入库");
        }
        List<OfflinePurchaseStorage> list = storageService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<OfflinePurchaseStorage> util = new ExportExcelUtils<OfflinePurchaseStorage>(moduleTable,new OfflinePurchaseStorage());
        return util.exportExcel(list, fieldList, "线下入库单", "export");
    }

    /**
     *@Description: 导出Excel导入模板
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:offlinepurchasestorage:import")
    @Log(title = "线下入库单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new OfflinePurchaseStorage());

        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<OfflinePurchaseStorage> util = new ExportExcelUtils<OfflinePurchaseStorage>(moduleTable,new OfflinePurchaseStorage());
        return util.exportExcel(null, fieldList, "线下入库单导入模板", "template");
    }


    /**
     * 导入并直接生成生效单据
     * @param infoItems 必要参数：对应实体类的json格式字符串（导入的字段用户内容）
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("storage:offlinepurchasestorage:import")
    @Log(title = "线下入库单导入", businessType = BusinessType.EXPORT)
    @PostMapping("/importdatapost")
    @ResponseBody
    public AjaxResult importData(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
		/*导入测试
		String infoItems = "[{'vGwMc':'岗位1','vHdRs':'1'},{'vGwMc':'岗位2','vHdRs':'2'}]";
		params.put("infoItems", infoItems);
		*/
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.saveImportData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 保存数据
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions(value={"storage:offlinepurchasestorage:add","storage:offlinepurchasestorage:edit","storage:offlinepurchasestorage:delete"},logical= Logical.OR)
    @Log(title = "线下入库单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.saveData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 流转
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:offlinepurchasestorage:flow")
    @Log(title = "线下入库单", businessType = BusinessType.FLOWGO)
    @PostMapping("/flowgopost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowGoSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.updateFlowGo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 退回
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("storage:offlinepurchasestorage:flow")
    @Log(title = "线下入库单", businessType = BusinessType.FLOWBACK)
    @PostMapping("/flowbackpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowBackSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.updateFlowBack(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }



    /**
     * @Description: 查询页 子列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("storage:offlinepurchasestorage:list")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {
//    	System.out.println("params---" + JSON.toJSONString(params));
        try {
            params.put("moduleTable", moduleTableZJ);
            params.put("entity", new ProductActiveComponent()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("toolBarWidth", 0);
            AjaxResult ajaxResult = new AjaxResult();
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            if (params.get("bid").toString().contains("XXCG")){
                mapList.put("sonList", storageService.selectOfflineOrderData(params));
            }else{
                mapList.put("sonList", storageService.selectOrderData(params));
            }

            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    /**
     * @Description: 修改审核状态
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-17 14:55
     */
    @RequiresPermissions("storage:offlinepurchasestorage:edit")
    @Log(title = "修改线下入库状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateType")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateType(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = storageService.updateType(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 删除
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-09-05 13:51
     */
    @RequiresPermissions("storage:offlinepurchasestorage:delete")
    @Log(title = "线下入库删除", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult productDelete(@RequestParam Map<String, Object> params){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= storageService.deleteData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 
     * @param params
     * @return
     */
    @PostMapping("/generateXxrkPDF")
    @ResponseBody
    public AjaxResult generateXxrkPDF(String guid){
        AjaxResult ajaxResult = new AjaxResult();
        try {
        	OfflinePurchaseStorage entity = storageService.queryByGuid(guid);
        	
        	String bid = entity.getBid();
        	
        	// 生成PDF到指定目录下
        	String dir = Global.getProfile();
        	String pdfFileName = "/XXRK/" + bid + ".pdf";
        	
			File file = new File(dir + "/XXRK/");
			if (!file.exists()) {
				file.mkdirs();
			}
        	
			String codeCgrk = entity.getBid();
			String codeCgdd = entity.getOrderID();
			String codeCompany = entity.getvGsBm();
			String nameCompany = entity.getvGsJc();
			String infoGoods = entity.getName();

			List<OfflinePurchaseStorage> listPurchaseStorage = storageService.selectOfflinePurchaseStorage(bid);
			
			List<PdfUtil.StockInXXDto.RowDto> rows = new ArrayList<PdfUtil.StockInXXDto.RowDto>();
			for(OfflinePurchaseStorage purchaseStorage : listPurchaseStorage) {
				String codeGoods = purchaseStorage.getsCode();
				String nameGoods = purchaseStorage.getsName();
				String num = purchaseStorage.getInqty().toString();
				rows.add(new PdfUtil.StockInXXDto.RowDto(codeGoods, nameGoods, num));
			}
			
        	PdfUtil.StockInXXDto dto = new PdfUtil.StockInXXDto(codeCgrk, codeCgdd, codeCompany, nameCompany, infoGoods, rows);
        	PdfUtil.generateStockInXX(dir, pdfFileName, dto);
        	
        	String data = "/profile" + pdfFileName;
            ajaxResult = AjaxResult.success(data);
        }catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


}